/**
 * 新增快递公司
 */

import React, { useState, useEffect } from 'react';
import CommonModal from '@/components/CommonModal';
import { Form, message, Select, Tooltip, Input } from 'antd';

import { getBaseExpressListOp, addExpressCompany } from '../../service';

const { Option } = Select;

export default ({ handleOk, handleCancel }) => {

  const [form] = Form.useForm();

  const [data, setData] = useState([]);

  const [open, setOpen] = useState(false);

  const [isOk, setIsOk] = useState(false);

  const onOk = () => {
    form.validateFields().then(val => {
      handleSubmit(val);
    })
  }

  useEffect(() => {
    setOpen(true);
    getExpressList();
  }, [])


  const getExpressList = async () => {
    START_LOADING()
    const { success, data } = await getBaseExpressListOp();
    END_LOADING()
    if (success) {
      setData(data);
    }
  }

  const handleSubmit = async val => {
    START_LOADING()
    let name = ''
    data.map(item => {
      if (val.expressId == item.id) {
        name = item.name
      }
    })
    const { success } = await addExpressCompany({
      ...val,
      expressName: name
    })
    END_LOADING()
    if (success) {
      message.success('新增成功！')
      setOpen(false);
      setIsOk(true);
    }
  }

  const onCancel = () => {
    setOpen(false);
  }

  const afterClose = () => {
    if (isOk) {
      handleOk();
    } else {
      handleCancel();
    }
  }

  const options = data.map(v =>
    <Option key={v.id} label={v.name} value={v.id}>
      <Tooltip title={v.name}>
        {v.name}
      </Tooltip>
    </Option>
  );

  return (
    <CommonModal
      title="新增快递公司"
      open={open}
      onOk={onOk}
      onCancel={onCancel}
      afterClose={afterClose}
      width={500}
    >
      <Form
        form={form}
        name='add-express-company'
        layout='horizontal'
      >
        <div style={{ display: 'flex', alignItems: 'baseline' }}>
          <Form.Item label="快递公司" name="expressId" rules={[{ required: true, message: '请选择快递公司' }]}>
            <Select placeholder='请选择快递公司' showSearch optionFilterProp="label" style={{ width: 140 }}>
              {options}
            </Select>
          </Form.Item>
          <span style={{ margin: '0 8px' }}> + </span>
          <Form.Item label="" name="custom" rules={[{ pattern: /^\S{0,8}$/, message: '不能超过8个字符' },]} style={{ width: 140 }}>
            <Input placeholder='不能超过8个字符' />
          </Form.Item>
        </div>
      </Form>
    </CommonModal>
  )
}